package tv_megazineplus

import grails.converters.*
import groovy.sql.Sql
import org.codehaus.groovy.runtime.TimeCategory



class RestController {
    
    def sendMailService
    def sendSmsService
    
    def index = { }
    
    def getChannelListJSON = {
        //não recebe nada
        // retorna a lista de canais
        def results = Channel2.list()
        def t1 = System.currentTimeMillis()
        
        
        render(contentType:"text/json") {
            canais = array {
                for(b in results) {
                    canal = {

                        id= b.id                                        
                        nome= b.channel_name
                        sigla= b.channel_sigla
                    }
                                        
                }
            }	
        }
                
        def t2 = System.currentTimeMillis()
        def tt = t2 - t1
        
        new Statistic(servico: Servicos.findByName('getChannelListJSON'), totalTime: tt, date: new Date()).save()
        
    }
    
    def getChannelListXML = {
        // 
        // retorna a lista de canais
        def t1 = System.currentTimeMillis()
        
        def results = Channel2.list()
        render(contentType:"text/xml") {
            canais = array {
                for(b in results) {
                    canal = {

                        id= b.id                                        
                        nome= b.channel_name
                        sigla= b.channel_sigla
                    }
                                        
                }
            }	
        }
        def tt = System.currentTimeMillis() - t1       
        new Statistic(servico: Servicos.findByName('getChannelListXML'), totalTime: tt, date: new Date()).save()
        
    }
    
    def getTokenToAlert = {
        //http://localhost:8080/TV_MegazinePlus/rest/getTokenToAlert?email=xxx@sapo.pt?email=true
        // por omissão manda sms
        // parametro: email do utilizador
        // paramentro: sms ou email (para receber token)
        def t1 = System.currentTimeMillis()
        def email = params.email
        def opcao = params.op
        
        def error = null
        def operacao
        
        def existe = Users.findByEmail(email)
        
        if(opcao == null){ // email é nulo
            operacao = 'sms'
        }else{ // email e especificado
            if(opcao == 'true'){ // email true
                operacao = 'email'
            }
            
            if(opcao != 'true' && opcao !=null){ // erro
                error = 'Only value possible for @params: op is: email=true'
            }
            
        }
       
        if(existe && error == null){
            ////////////////////////// SEND TOKEN HERE
            def ramdomNumber = ramdom(8)
            use(TimeCategory){
                new Token(user: existe, token: ramdomNumber, expira: new Date() + 30.minutes).save() 
            }//Users é o existe
                
            def sms = 'O seu token de acesso provisório (30min) é: ' + ramdomNumber             
                
            if(operacao == 'email'){
                sendMailService.serviceMethod(existe.email, 'TvMg+ Token de Acesso', sms)
            }
            
            if(operacao == 'sms'){
                sendSmsService.serviceMethod('TvMgP', existe.phoneNumber, sms)
            }
            def tt = System.currentTimeMillis() - t1       
            new Statistic(servico: Servicos.findByName('getTokenToAlert'), totalTime: tt, date: new Date()).save()
            
            //////////////////////////////////////////
            
                
        }else{ // render error
                
            render(contentType:"text/json") {
                books = {
                    if(error!=null){
                        errorEmailParams = error
                    }
                    errorEmail = 'That email doesnt exist ' 
                    operação = 'getTokenToAlert'
                                
		}	
            }
        }
        
                
    }
    
    
    def getProgrammsListJSON = {
        //http://localhost:8080/TV_MegazinePlus/rest/getProgrammsListJSON?channelID=10
        // parametro: id
        def channelID = params.channelID
        def canal = Channel2.get(channelID)
        def t1 = System.currentTimeMillis()
        def progs = Programmation.findAllByProg_channel(canal)
        
        render(contentType:"text/json") {
            programas = array {
                for(p in progs) {
                    programa = {
                        id = p.id
                        title = p.prog_title
                        start = p.prog_start
                        end = p.prog_end
                                        
                    }
                                        
                }
            }	
        }
        def tt = System.currentTimeMillis() - t1        
        new Statistic(servico: Servicos.findByName('getProgrammsListJSON'), totalTime: tt, date: new Date()).save()
    }
    
    def getProgrammsListXML = {
        //http://localhost:8080/TV_MegazinePlus/rest/getProgrammsListJSON?channelID=10
        // parametro: id
        def channelID = params.channelID
        def canal = Channel2.get(channelID)
        def t1 = System.currentTimeMillis()
        
        def progs = Programmation.findAllByProg_channel(canal)
        
        render(contentType:"text/xml") {
            programas = array {
                for(p in progs) {
                    programa = {
                        id = p.id
                        title = p.prog_title
                        start = p.prog_start
                        end = p.prog_end
                                        
                    }
                                        
                }
            }	
        }
        def tt = System.currentTimeMillis() - t1        
        new Statistic(servico: Servicos.findByName('getProgrammsListXML'), totalTime: tt, date: new Date()).save()
    }
    
    def createAlertJSON = {
        // params: token
        // Programmation program // String personalMessage //Date horaDispara //String tipo
        // createAlertJSON?token=asasasas&progId=121&tipo=sms&tempo=5&pm=sdsdsdsndjbdsb
        def t1 = System.currentTimeMillis()
        def erro = ''
                
        if(params.tipo != 'sms' && params.tipo != 'email')
        error = error + 'tipo, '
        if(!params.tempo.isInteger())
        error = error + 'tempo, '
        if(!params.pm)
        error = error + 'tempo, '
        
        def token = Token.findByToken(params.token)
        def agora = new Date()
        
        if(token && agora.before(token.expira)){
            def dispara
            use(TimeCategory){
                dispara = Programmation.get(params.progId).prog_start - params.tempo.toInteger().minutes
            }
            
            if(erro.size() == 0){
                new Alert(user: token.user, program: Programmation.get(params.progId), personalMessage: params.pm, horaDispara: dispara, tipo: params.tipo, sent: 0).save(failOnError: true)
            
                def tt = System.currentTimeMillis() - t1        
                new Statistic(servico: Servicos.findByName('getProgrammsListXML'), totalTime: tt, date: new Date()).save()    
                
                render 'sucess'
            }else{
                render 'params error!'
            }   
            
        }else{
            render 'erro'
        }
        
        
       
        
        //Integer sent
    }
    
    def getStatsJSON = {
        // params@ dataInicio, datafim
        
        def stats = Statistic.findByDateBetween(params.inicio, params.fim)
        def statss = []
        
       def sql = Sql.newInstance( 'jdbc:postgresql://192.168.56.101:5432/ad', 'grails',
                       'tvmagazine', 'org.postgresql.Driver' )
        sql.eachRow( 'select name, description, media,frequencia from servicos t1 join (select servico_id ,avg(total_time) as media ,COUNT(servico_id) as frequencia FROM statistic group by servico_id) t2 on t1.id = t2.servico_id' ) 
           statss.add(new Estatistica(name:it.name,description:it.description,media:it.media,frequencia:it.frequencia))
        
    }
        
        
        
        
//        render(contentType:"text/json") {
//            stats = array {
//                for(b in stats) {
//                    canal = {
//
//                        id= b.id                                        
//                        nome= b.channel_name
//                        sigla= b.channel_sigla
//                    }
//                                        
//                }
//            }	
        
    
    
    


    def ramdom (nnn){
        def num = 10 * nnn
        Random random = new Random()
        random.nextInt(10 * num)
    }

    def teste ={
        def data1 = new Date()
        def data2 = new Date() - 5
        
        List<Estatistica> aa = Estatistica.executeQuery("select name, description, media,frequencia from TvMagazinePlus.dbo.servicos as t1 join (SELECT TOP 1000 [servico_id] ,avg([total_time]) as 'media' ,COUNT([servico_id]) as 'frequencia' FROM [TvMagazinePlus].[dbo].[statistic] where date between ? and ? group by [servico_id]) as t2 on t1.id = t2.servico_id)", [data1, data1]);

        render aa as JSON
    }
}

class Channel_ {
    String sigla
    String nome
    
    String getSigla(){
        silga
    }
    
    String getNome(){
        nome
    }
}

